#include "mktableview.h"
#include "mkfiletablemodel.h"
#include "mkdelegates.h"

#include "mkcore/mkcore.h"

#include <QHeaderView>
#include <QApplication>

#include <QDebug>

MKTableView::MKTableView()
{
	pModel = (MKTableModel*)(new MKFileTableModel(this));

	setModel(pModel);

#ifdef QT5
	horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
#else
	horizontalHeader()->setResizeMode(QHeaderView::Stretch);
#endif

	setItemDelegateForColumn(C_Date, MKFactoryDelegate::delegateFromType(C_Date));
	setItemDelegateForColumn(C_Type, MKFactoryDelegate::delegateFromType(C_Type));
	setItemDelegateForColumn(C_Category, MKFactoryDelegate::delegateFromType(C_Category));

	connect(pModel, SIGNAL(dataChanged(QModelIndex,QModelIndex)),
			this, SLOT(onDataChanged(const QModelIndex&, const QModelIndex&)));
}

bool MKTableView::onAddRow()
{
	return pModel->insertRow(pModel->rowCount(QModelIndex()));
}

bool MKTableView::onRemoveRow()
{
	QModelIndex index = currentIndex();
	if (!index.isValid())
	{
		return false;
	}

	return pModel->removeRow(index.row());
}

void MKTableView::onDataChanged(const QModelIndex &leftTop, const QModelIndex &rightBottom)
{
	if  ((leftTop == rightBottom) &&
		((leftTop.column() == C_Date) || leftTop.column() == C_Category))
	{
		return;
	}
	emit balanceChanged(pModel->currentBalance());
}

bool MKTableView::save(QString fileName)
{
	return pModel->save(fileName);
}

bool MKTableView::load(QString fileName)
{
	return pModel->load(fileName);
}

QMap<quint8, quint32> MKTableView::costsForTypes()
{
	return pModel->costsForTypes();
}

QMap<quint8, QMap<quint8, quint32> > MKTableView::costsForCategories()
{
	return pModel->costsForCategories();
}

